package com.net.framework.help.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/***
 * 图片保存工具类
 *
 * @author zhangxiaobin
 */
public class SaveImageUitle {
    private static SaveImageListener saveImageListener;
    public static String SAVE_ALBUM_PATH;

    public static String path(Context mContext) {
        if (null == SAVE_ALBUM_PATH) {
            SAVE_ALBUM_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + mContext.getPackageName() + "/File/";
        }
        return SAVE_ALBUM_PATH;
    }

    /**
     * 保存图片
     *
     * @param mContext  上下文
     * @param imagename 图片的存放目标文件（图片名称）
     * @param bitmap    图片的位图
     */
    public static void saveImage(Context mContext, String imagename, Bitmap bitmap, SaveImageListener saveListener) {
        SaveImageUitle.saveImageListener = saveListener;
        saveImage(mContext, imagename, bitmap, true);
    }

    public static void saveImage(Context mContext, String imagename, Bitmap bitmap, SaveImageListener saveListener, boolean isShowToast) {
        SaveImageUitle.saveImageListener = saveListener;
        saveImage(mContext, imagename, bitmap, isShowToast);
    }

    public static void saveImage(Context mContext, String imagename, Bitmap bitmap) {
        saveImage(mContext, imagename, bitmap, true);
    }

    /**
     * 保存图片
     *
     * @param mContext  上下文
     * @param imagename 图片的存放目标文件（图片名称）
     * @param bitmap    图片的位图
     */

    public static void saveImage(Context mContext, String imagename, Bitmap bitmap, boolean isShowToast) {
        try {
            if (null != bitmap) {
                saveFile(mContext, bitmap, imagename + ".jpg", isShowToast);
            } else {
                UIUtils.shortToast("保存图片失败");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch bloc
            e.printStackTrace();
        }

    }

    public static void saveFile(Context context, Bitmap bm, String fileName, boolean isShowToast) {
        // 图片保存目录地址
        String PATH = path(context);
        File dirFile = new File(PATH);// 保存目标文件夹
        if (!dirFile.exists()) {// 若没有创建该文件夹
            dirFile.mkdirs();// 创建
        }
        try {
            String pth = PATH + fileName;
            File myCaptureFile = new File(pth);
            if (myCaptureFile.exists()) {
                if (isShowToast) {
                    UIUtils.shortToast("该图片已存在，无需再保存哦~");
                }
            } else {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
                if (bm.isRecycled()) {
                    bm.recycle();
                }
                if (isShowToast) {
                    UIUtils.longToast("保存成功，图片位置：" + pth);
                }
                if (null != saveImageListener) {
                    saveImageListener.onSaveComplete(pth);
                }
//                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                Uri uri = Uri.fromFile(new File(pth));
//                intent.setData(uri);
//                context.sendBroadcast(intent);
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), myCaptureFile.getAbsolutePath(), myCaptureFile.getName(), null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(myCaptureFile.getPath()))));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

//    public static Uri getUri(Context mContext, String imagename, Bitmap bitmap) {
//        Uri uri = null;
//        if (null != bitmap) {
//            uri = convertUri(mContext, bitmap, imagename + ".jpg");
//        } else {
//            UIUtils.shortToast("图片分享失败");
//        }
//        return uri;
//    }

    public static Uri convertUri(Context context, Bitmap bm, String fileName) {
        Uri uri = null;
        // 图片保存目录地址
        String PATH = path(context);
        File dirFile = new File(PATH);// 保存目标文件夹
        if (!dirFile.exists()) {// 若没有创建该文件夹
            dirFile.mkdirs();// 创建
        }
        try {
            String pth = PATH + fileName;
            File myCaptureFile = new File(pth);
            if (myCaptureFile.exists()) {
                uri = Uri.fromFile(myCaptureFile);
            } else {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
                if (bm.isRecycled()) {
                    bm.recycle();
                }
                uri = Uri.fromFile(new File(pth));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return uri;
    }

    /**
     * 获取视频的封面图片
     *
     * @param filePath
     * @return
     */
    public String getVideoThumbnail(Context context, String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return convertUri(context, bitmap, "video_convert.jpg").toString();
    }

    /**
     * 监听保存图片
     */
    public interface SaveImageListener {
        void onSaveComplete(String imagePath);
    }
}
